package com.example.neutonote2;

import android.os.Bundle;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.app.AlertDialog;

import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;

import com.example.neutonote2.databinding.ActivityMainBinding;
import com.example.neutonote2.viewmodel.TagViewModel;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    private ActivityMainBinding binding;
    private NavController navController;
    private FloatingActionButton fabAi; 

    // 定义功能标志常量
    public static final String AI_FUNCTION_KEY = "ai_function";
    public static final int AI_FUNCTION_NONE = 0;
    public static final int AI_FUNCTION_SUMMARY = 1;
    public static final int AI_FUNCTION_OPTIMIZE = 2;
    public static final int AI_FUNCTION_KEYPOINTS = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 在应用启动时清理错误标签
        cleanInvalidTags();

        setSupportActionBar(binding.appBarMain.toolbar);
        binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 导航到添加新笔记界面
                navController.navigate(R.id.action_global_note_edit);
            }
        });
        
        // 使用findViewById找到AI助手按钮
        fabAi = findViewById(R.id.fab_ai);
        
        // 设置AI助手按钮点击事件
        fabAi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAIFeaturesDialog();
            }
        });
        
        DrawerLayout drawer = binding.drawerLayout;
        NavigationView navigationView = binding.navView;
        
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_all_notes, R.id.nav_work, R.id.nav_study, R.id.nav_life, 
                R.id.nav_review, R.id.nav_tags, R.id.nav_categories)
                .setOpenableLayout(drawer)
                .build();
        
        // 初始化NavController
        navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

        // 监听导航事件，设置不同页面的导航图标行为
        navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
            // 检查当前目的地是否属于AppBarConfiguration中定义的顶级目的地
            if (mAppBarConfiguration.getTopLevelDestinations().contains(destination.getId())) {
                // 如果是顶级页面，保持默认的抽屉菜单行为
                binding.appBarMain.toolbar.setNavigationOnClickListener(v -> {
                    if (drawer.isDrawerOpen(navigationView)) {
                        drawer.closeDrawer(navigationView);
                    } else {
                        drawer.openDrawer(navigationView);
                    }
                });
            } else {
                // 如果是子页面（显示返回箭头），点击时返回主页面
                binding.appBarMain.toolbar.setNavigationOnClickListener(v -> {
                    navController.navigate(R.id.nav_all_notes);
                });
            }
        });
    }
    
    /**
     * 清理无效标签
     */
    private void cleanInvalidTags() {
        try {
            TagViewModel tagViewModel = new ViewModelProvider(this).get(TagViewModel.class);
            tagViewModel.cleanInvalidTags();
        } catch (Exception e) {
            // 忽略异常，确保不会影响应用启动
        }
    }
    
    /**
     * 显示AI功能选择对话框
     */
    private void showAIFeaturesDialog() {
        // 显示AI功能菜单
        new AlertDialog.Builder(this)
                .setTitle("AI智能功能")
                .setItems(new String[]{"生成摘要", "优化笔记", "提取关键点"}, (dialog, which) -> {
                    switch (which) {
                        case 0: // 生成摘要
                            // 如果当前已经在笔记编辑页面，直接发送通知
                            if (navController.getCurrentDestination().getId() == R.id.nav_note_edit) {
                                navController.getCurrentBackStackEntry().getSavedStateHandle().set(AI_FUNCTION_KEY, AI_FUNCTION_SUMMARY);
                                Toast.makeText(this, "正在生成摘要...", Toast.LENGTH_SHORT).show();
                            } else {
                                // 否则，创建新笔记并设置标记，使其打开后自动执行摘要功能
                                Bundle args = new Bundle();
                                args.putInt(AI_FUNCTION_KEY, AI_FUNCTION_SUMMARY);
                                navController.navigate(R.id.action_global_note_edit, args);
                            }
                            break;
                        case 1: // 优化笔记
                            // 如果当前已经在笔记编辑页面，直接发送通知
                            if (navController.getCurrentDestination().getId() == R.id.nav_note_edit) {
                                navController.getCurrentBackStackEntry().getSavedStateHandle().set(AI_FUNCTION_KEY, AI_FUNCTION_OPTIMIZE);
                                Toast.makeText(this, "正在优化笔记...", Toast.LENGTH_SHORT).show();
                            } else {
                                // 否则，创建新笔记并设置标记，使其打开后自动执行优化功能
                                Bundle args = new Bundle();
                                args.putInt(AI_FUNCTION_KEY, AI_FUNCTION_OPTIMIZE);
                                navController.navigate(R.id.action_global_note_edit, args);
                            }
                            break;
                        case 2: // 提取关键点
                            // 如果当前已经在笔记编辑页面，直接发送通知
                            if (navController.getCurrentDestination().getId() == R.id.nav_note_edit) {
                                navController.getCurrentBackStackEntry().getSavedStateHandle().set(AI_FUNCTION_KEY, AI_FUNCTION_KEYPOINTS);
                                Toast.makeText(this, "正在提取关键点...", Toast.LENGTH_SHORT).show();
                            } else {
                                // 否则，创建新笔记并设置标记，使其打开后自动执行提取关键点功能
                                Bundle args = new Bundle();
                                args.putInt(AI_FUNCTION_KEY, AI_FUNCTION_KEYPOINTS);
                                navController.navigate(R.id.action_global_note_edit, args);
                            }
                            break;
                    }
                })
                .setCancelable(true)
                .create()
                .show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_deepseek_settings) {
            try {
                // 使用已经初始化的navController
                navController.navigate(R.id.nav_deepseek_settings);
                return true;
            } catch (Exception e) {
                Snackbar.make(binding.getRoot(), "打开设置失败: " + e.getMessage(), Snackbar.LENGTH_LONG).show();
                return true;
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
}